using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace OrdersApi.Controllers;

/// <summary>
/// 订单 API - OneAuthCenter 集成示例
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    private static readonly List<Order> _orders = new()
    {
        new Order { Id = 1, ProductName = "iPhone 15 Pro", Quantity = 1, Price = 7999, Status = "已发货" },
        new Order { Id = 2, ProductName = "MacBook Pro", Quantity = 1, Price = 14999, Status = "处理中" },
        new Order { Id = 3, ProductName = "AirPods Pro", Quantity = 2, Price = 1999, Status = "已完成" }
    };

    /// <summary>
    /// 获取所有订单（需要认证）
    /// </summary>
    /// <returns>订单列表</returns>
    [HttpGet]
    [Authorize]  // 需要认证
    public IActionResult GetAll()
    {
        // 获取当前用户信息
        var userId = User.FindFirst("sub")?.Value;
        var username = User.FindFirst("name")?.Value ?? User.FindFirst("preferred_username")?.Value;
        var email = User.FindFirst("email")?.Value;
        
        return Ok(new
        {
            message = "获取订单成功",
            currentUser = new
            {
                id = userId,
                name = username,
                email = email
            },
            orders = _orders
        });
    }

    /// <summary>
    /// 根据 ID 获取订单（需要 orders.read scope）
    /// </summary>
    [HttpGet("{id}")]
    [Authorize(Policy = "OrdersRead")]
    public IActionResult GetById(int id)
    {
        var order = _orders.FirstOrDefault(o => o.Id == id);
        if (order == null)
        {
            return NotFound($"订单 {id} 不存在");
        }
        
        return Ok(order);
    }

    /// <summary>
    /// 创建订单（需要 orders.create scope）
    /// </summary>
    [HttpPost]
    [Authorize(Policy = "OrdersCreate")]
    public IActionResult Create([FromBody] CreateOrderRequest request)
    {
        var newOrder = new Order
        {
            Id = _orders.Max(o => o.Id) + 1,
            ProductName = request.ProductName,
            Quantity = request.Quantity,
            Price = request.Price,
            Status = "待处理"
        };
        
        _orders.Add(newOrder);
        
        var userId = User.FindFirst("sub")?.Value;
        return CreatedAtAction(nameof(GetById), new { id = newOrder.Id }, new
        {
            message = $"订单创建成功（操作者: {userId}）",
            order = newOrder
        });
    }

    /// <summary>
    /// 删除订单（需要 orders.delete scope 和 Admin 角色）
    /// </summary>
    [HttpDelete("{id}")]
    [Authorize(Policy = "OrdersDelete")]
    public IActionResult Delete(int id)
    {
        var order = _orders.FirstOrDefault(o => o.Id == id);
        if (order == null)
        {
            return NotFound($"订单 {id} 不存在");
        }
        
        _orders.Remove(order);
        
        var userId = User.FindFirst("sub")?.Value;
        return Ok(new
        {
            message = $"订单删除成功（操作者: {userId}）",
            deletedOrder = order
        });
    }

    /// <summary>
    /// 公开端点（无需认证）
    /// </summary>
    [HttpGet("public/stats")]
    [AllowAnonymous]
    public IActionResult GetPublicStats()
    {
        return Ok(new
        {
            message = "公开统计数据",
            totalOrders = _orders.Count,
            totalValue = _orders.Sum(o => o.Price * o.Quantity),
            disclaimer = "此端点无需认证即可访问"
        });
    }

    /// <summary>
    /// 测试 Token 信息
    /// </summary>
    [HttpGet("test/token-info")]
    [Authorize]
    public IActionResult GetTokenInfo()
    {
        var claims = User.Claims.Select(c => new
        {
            type = c.Type,
            value = c.Value
        }).ToList();
        
        return Ok(new
        {
            message = "Token 信息",
            isAuthenticated = User.Identity?.IsAuthenticated ?? false,
            authenticationType = User.Identity?.AuthenticationType,
            claims = claims
        });
    }
}

/// <summary>
/// 订单模型
/// </summary>
public class Order
{
    public int Id { get; set; }
    public string ProductName { get; set; } = string.Empty;
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public string Status { get; set; } = string.Empty;
}

/// <summary>
/// 创建订单请求
/// </summary>
public class CreateOrderRequest
{
    public string ProductName { get; set; } = string.Empty;
    public int Quantity { get; set; }
    public decimal Price { get; set; }
}

